package com.github.easyms.server.service.auth.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.easyms.common.entity.auth.Role;
import com.github.easyms.common.entity.auth.RoleMenu;
import com.github.easyms.common.entity.auth.User;
import com.github.easyms.server.mapper.auth.RoleMenuMapper;
import com.github.easyms.server.service.auth.RoleMenuService;
import org.apache.shiro.SecurityUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.sql.Wrapper;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 角色-菜单关联业务实现
 *
 * @author Leo.Liao
 * @date 2020-04-29 00:11:48
 */
@Service
public class RoleMenuServiceImpl extends ServiceImpl<RoleMenuMapper, RoleMenu> implements RoleMenuService {

    @Resource
    private RoleMenuMapper roleMenuMapper;

    @Override
    public List<String> selectMenuIdsByRoleId(String roleId) {
        List<RoleMenu> roleMenus = roleMenuMapper.selectList(Wrappers.<RoleMenu>lambdaQuery()
                .eq(RoleMenu::getRoleId, roleId)
                .select(RoleMenu::getMenuId)
        );
        List<String> menuIds = new ArrayList<>();
        roleMenus.forEach(roleMenu -> menuIds.add(roleMenu.getMenuId()));
        return menuIds;
    }

    @Override
    public void updateRoleMenus(String roleId, List<String> menuIds, String editUserId) {
        // 删除旧的授权数据
        roleMenuMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId,roleId));
        for(String menuId:menuIds){
            RoleMenu roleMenu = new RoleMenu();
            roleMenu.setRoleId(roleId);
            roleMenu.setMenuId(menuId);
            roleMenu.setCreateTime(LocalDateTime.now());
            roleMenu.setEditUser(editUserId);
            roleMenuMapper.insert(roleMenu);
        }
    }

    @Override
    public void deleteByMenuId(String menuId) {
        roleMenuMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getMenuId,menuId));
    }

    @Override
    public void deleteByRoleId(String roleId) {
        roleMenuMapper.delete(Wrappers.<RoleMenu>lambdaQuery().eq(RoleMenu::getRoleId,roleId));
    }

}
